package com.waijiaojun.tpo.web.account;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.waijiaojun.tpo.service.account.ShiroDbRealm;
import com.waijiaojun.tpo.service.account.WeixinOAuthAuthenticationFilter;
import com.waijiaojun.tpo.service.account.WeixinOAuthToken;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * <p>
 * 真正登录的POST请求由Filter完成,
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String login() {
        logger.info("login");
        //如果已登录，跳转到首页，否则进入登录页面
        if (SecurityUtils.getSubject().isAuthenticated()) {
            logger.info("login 已登录");
            return "redirect:/";
        } else {
            logger.info("login 跳转到oauthLogin页面");
            return "oauthLogin";
        }
    }

    @RequestMapping(value = "oauthFailure", method = RequestMethod.GET)
    public String fail(@RequestParam(WeixinOAuthAuthenticationFilter.ERROR_CODE_PARAM) String errcode,
                       @RequestParam(WeixinOAuthAuthenticationFilter.ERROR_MSG_PARAM) String errmsg, Model model) {
        model.addAttribute(WeixinOAuthAuthenticationFilter.ERROR_CODE_PARAM, errcode);
        model.addAttribute(WeixinOAuthAuthenticationFilter.ERROR_MSG_PARAM, errmsg);
        logger.info("oauthFailure");
        return "oauthFailure";
    }

    /**
     * 从浏览器端登录入口，仅仅供开发调试页面时使用
     * <p>
     * http://wx.wonderlink.com.cn:80/ocw/login/webLogin/oMBADjx7A-WOHIiVselNph0Gqqfo
     *
     * @param openid
     * @param model
     * @return
     */
    @RequestMapping(value = "webLogin/{openid}", method = RequestMethod.GET)
    public String webLogin(@PathVariable("openid") String openid, Model model) {
        logger.info("webLogin ==========>{openid：" + openid + "}");
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            logger.info("login---------未登录");
            // 登录系统
            logger.info("login---------已绑定微信，根据openId登录系统：openId:" + openid);
            WeixinOAuthToken token = new WeixinOAuthToken(ShiroDbRealm.TEST_TOKEN, openid);
            currentUser.login(token);

        } else {
            logger.info("logine---------已登录");
        }
        return "redirect:/";
    }

}
